package com.windea.study.kotlin.game.tankwar2.model

import com.windea.study.kotlin.game.tankwar2.*
import com.windea.study.kotlin.game.tankwar2.core.*
import com.windea.study.kotlin.game.tankwar2.enums.*
import com.windea.study.kotlin.game.tankwar2.interfaces.*

/**子弹。*/
class Bullet(
	override val owner: Tank,
	override val direction: Direction
) : Effect(), Attackable, Sufferable, AutoMovable {
	override var x: Int = 0
	override var y: Int = 0
	override val width: Int
	override val height: Int
	override val attack: Int = 1
	override var health: Int = 1
	override val speed: Int = 12
	
	private val imagePath: String = when(direction) {
		Direction.Up -> "img/shot_top.gif"
		Direction.Down -> "img/shot_bottom.gif"
		Direction.Left -> "img/shot_left.gif"
		Direction.Right -> "img/shot_right.gif"
	}
	private var isDestroyed = false
	
	init {
		//先计算宽度和高度
		val widthHeightPair = Painter.size(imagePath)
		width = widthHeightPair.first
		height = widthHeightPair.second
		
		val tankX = owner.x
		val tankY = owner.y
		val tankWidth = owner.width
		val tankHeight = owner.height
		
		var bulletX = tankX + (tankWidth - width) / 2
		var bulletY = tankY - height / 2
		
		when(direction) {
			Direction.Up -> {
				bulletX = tankX + (tankWidth - width) / 2
				bulletY = tankY - height / 2
			}
			Direction.Down -> {
				bulletX = tankX + (tankWidth - width) / 2
				bulletY = tankY + tankHeight - height / 2
			}
			Direction.Left -> {
				bulletX = tankX - width / 2
				bulletY = tankY + (tankHeight - height) / 2
			}
			Direction.Right -> {
				bulletX = tankX + tankWidth - width / 2
				bulletY = tankY + (tankHeight - height) / 2
			}
		}
		
		x = bulletX
		y = bulletY
	}
	
	override fun draw() {
		Painter.drawImage(imagePath, x, y)
	}
	
	override fun onAttack(entities: MutableList<Entity>) {
		isDestroyed = true
	}
	
	override fun onSuffer(other: Attackable, entities: MutableList<Entity>) {
		//FIXED 修正子弹爆炸位置不正确的BUG
		entities += Blast(x + GameConfig.block / 2, y - GameConfig.block / 2)
	}
	
	override fun onAutoMove(entities: MutableList<Entity>) {
		//根据自己的方向，来改变自己的x和y
		when(direction) {
			Direction.Up -> y -= speed
			Direction.Down -> y += speed
			Direction.Left -> x -= speed
			Direction.Right -> x += speed
		}
	}
	
	override fun isDestroyed(): Boolean {
		//TODO 未检查
		return when {
			//子弹打到墙上后，子弹要销毁掉
			isDestroyed -> true
			//子弹在脱离了屏幕后，需要被销毁
			x < -width -> true
			x > GameConfig.width -> true
			y < -height -> true
			y > GameConfig.height -> true
			else -> false
		}
	}
}
